package com.sinosoft.lingkang.happyproxy.example;

import com.sinosoft.lingkang.happyproxy.server.DefaultHappyProxyServer;
import com.sinosoft.lingkang.happyproxy.server.HttpAuthorization;
import com.sinosoft.lingkang.happyproxy.server.HttpProxyServerFlowCount;
import com.sinosoft.lingkang.happyproxy.server.HttpProxyServerRequestFilter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpRequest;
import java.io.UnsupportedEncodingException;

/**
 * @Author 绫小路
 * @Date 2021/2/22
 */
public class HappyProxyServerExample {

  public static void main(String[] args) {
    new DefaultHappyProxyServer()
        .setPort(8888)
        .setAuthorization(new HttpAuthorization() {
          @Override
          public boolean authorization(String username, String password) {
            return true;
          }
        })
        .setRequestFilter(new HttpProxyServerRequestFilter() {
          @Override
          public boolean doFilter(HttpRequest request, Channel inputChannel, String host, int port) {
            if ("lingkang.top".equals(host)) {
              String response = "HTTP/1.1 200 OK\n"
                  + "content-type: text/html;charset=utf-8\n"
                  + "content-length: 86\n\n"
                  + "<html><body>禁止访问lingkang.top！<script>alert('嘿嘿!')</script></body></html>";
              ByteBuf byteBuf = null;
              try {
                byteBuf = Unpooled.wrappedBuffer(response.getBytes("UTF-8"));
              } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
              }
              inputChannel.writeAndFlush(byteBuf);
              return false;
            }
            return true;
          }
        })
        .setHttpProxyServerFlowCount(new HttpProxyServerFlowCount() {
          @Override
          public void upLoadByte(int up) {
            System.out.println(up);
          }

          @Override
          public void downLoadByte(int down) {
            System.out.println(down);
          }
        })
        .start();
  }
}
